/**
 * 组件生命周期管理器
 * 跟踪组件状态，防止在组件销毁后进行DOM操作
 */

class ComponentLifecycleManager {
  constructor() {
    this.components = new Map()
    this.pendingOperations = new Map()
    this.cleanupTasks = new Map()
  }

  /**
   * 注册组件
   * @param {Object} component - 组件实例
   * @param {Object} options - 配置选项
   */
  registerComponent(component, options = {}) {
    const componentId = this.generateComponentId(component)
    
    const componentState = {
      id: componentId,
      component,
      isActive: true,
      isMounted: false,
      isDestroyed: false,
      registeredAt: Date.now(),
      lastActivity: Date.now(),
      options: {
        autoCleanup: true,
        trackActivity: true,
        ...options
      }
    }

    this.components.set(componentId, componentState)
    this.setupLifecycleHooks(component, componentId)
    
    console.log(`组件已注册: ${componentId}`)
    return componentId
  }

  /**
   * 设置生命周期钩子
   * @param {Object} component - 组件实例
   * @param {string} componentId - 组件ID
   */
  setupLifecycleHooks(component, componentId) {
    // 微信小程序生命周期
    if (this.isMiniProgramComponent(component)) {
      this.setupMiniProgramHooks(component, componentId)
    }
    // Vue组件生命周期
    else if (this.isVueComponent(component)) {
      this.setupVueHooks(component, componentId)
    }
  }

  /**
   * 设置微信小程序生命周期钩子
   * @param {Object} component - 小程序组件实例
   * @param {string} componentId - 组件ID
   */
  setupMiniProgramHooks(component, componentId) {
    // 保存原始生命周期方法
    const originalOnLoad = component.onLoad
    const originalOnShow = component.onShow
    const originalOnHide = component.onHide
    const originalOnUnload = component.onUnload

    // 重写 onLoad
    component.onLoad = function(options) {
      this._lifecycleManager_componentId = componentId
      this._lifecycleManager_instance = this
      
      const state = this._getComponentState(componentId)
      if (state) {
        state.isMounted = true
        state.lastActivity = Date.now()
      }

      if (originalOnLoad) {
        originalOnLoad.call(this, options)
      }
    }.bind(this)

    // 重写 onShow
    component.onShow = function() {
      const state = this._getComponentState(componentId)
      if (state) {
        state.isActive = true
        state.lastActivity = Date.now()
      }

      if (originalOnShow) {
        originalOnShow.call(component)
      }
    }.bind(this)

    // 重写 onHide
    component.onHide = function() {
      const state = this._getComponentState(componentId)
      if (state) {
        state.isActive = false
        state.lastActivity = Date.now()
      }

      if (originalOnHide) {
        originalOnHide.call(component)
      }
    }.bind(this)

    // 重写 onUnload
    component.onUnload = function() {
      this.markDestroyed(componentId)

      if (originalOnUnload) {
        originalOnUnload.call(component)
      }
    }.bind(this)
  }

  /**
   * 设置Vue组件生命周期钩子
   * @param {Object} component - Vue组件实例
   * @param {string} componentId - 组件ID
   */
  setupVueHooks(component, componentId) {
    // 监听 mounted
    const originalMounted = component.$options.mounted || []
    const mountedHandlers = Array.isArray(originalMounted) ? originalMounted : [originalMounted]
    
    component.$options.mounted = [
      ...mountedHandlers,
      () => {
        const state = this.components.get(componentId)
        if (state) {
          state.isMounted = true
          state.lastActivity = Date.now()
        }
      }
    ]

    // 监听 activated (keep-alive)
    const originalActivated = component.$options.activated || []
    const activatedHandlers = Array.isArray(originalActivated) ? originalActivated : [originalActivated]
    
    component.$options.activated = [
      ...activatedHandlers,
      () => {
        const state = this.components.get(componentId)
        if (state) {
          state.isActive = true
          state.lastActivity = Date.now()
        }
      }
    ]

    // 监听 deactivated (keep-alive)
    const originalDeactivated = component.$options.deactivated || []
    const deactivatedHandlers = Array.isArray(originalDeactivated) ? originalDeactivated : [originalDeactivated]
    
    component.$options.deactivated = [
      ...deactivatedHandlers,
      () => {
        const state = this.components.get(componentId)
        if (state) {
          state.isActive = false
        }
      }
    ]

    // 监听 beforeDestroy
    const originalBeforeDestroy = component.$options.beforeDestroy || []
    const destroyHandlers = Array.isArray(originalBeforeDestroy) ? originalBeforeDestroy : [originalBeforeDestroy]
    
    component.$options.beforeDestroy = [
      ...destroyHandlers,
      () => this.markDestroyed(componentId)
    ]
  }

  /**
   * 标记组件为活跃状态
   * @param {string} componentId - 组件ID
   */
  markActive(componentId) {
    const state = this.components.get(componentId)
    if (state && !state.isDestroyed) {
      state.isActive = true
      state.lastActivity = Date.now()
    }
  }

  /**
   * 标记组件为非活跃状态
   * @param {string} componentId - 组件ID
   */
  markInactive(componentId) {
    const state = this.components.get(componentId)
    if (state) {
      state.isActive = false
      state.lastActivity = Date.now()
    }
  }

  /**
   * 标记组件为销毁状态
   * @param {string} componentId - 组件ID
   */
  markDestroyed(componentId) {
    const state = this.components.get(componentId)
    if (state) {
      state.isActive = false
      state.isMounted = false
      state.isDestroyed = true
      state.lastActivity = Date.now()

      // 执行清理任务
      this.executeCleanupTasks(componentId)
      
      // 取消待处理的操作
      this.cancelPendingOperations(componentId)

      console.log(`组件已销毁: ${componentId}`)

      // 延迟删除组件状态
      setTimeout(() => {
        this.components.delete(componentId)
        this.cleanupTasks.delete(componentId)
        this.pendingOperations.delete(componentId)
      }, 1000)
    }
  }

  /**
   * 检查组件是否活跃
   * @param {string} componentId - 组件ID
   * @returns {boolean}
   */
  isActive(componentId) {
    const state = this.components.get(componentId)
    return state && state.isActive && state.isMounted && !state.isDestroyed
  }

  /**
   * 检查组件是否已挂载
   * @param {string} componentId - 组件ID
   * @returns {boolean}
   */
  isMounted(componentId) {
    const state = this.components.get(componentId)
    return state && state.isMounted && !state.isDestroyed
  }

  /**
   * 检查组件是否已销毁
   * @param {string} componentId - 组件ID
   * @returns {boolean}
   */
  isDestroyed(componentId) {
    const state = this.components.get(componentId)
    return !state || state.isDestroyed
  }

  /**
   * 添加清理任务
   * @param {string} componentId - 组件ID
   * @param {Function} cleanupFn - 清理函数
   */
  addCleanupTask(componentId, cleanupFn) {
    if (!this.cleanupTasks.has(componentId)) {
      this.cleanupTasks.set(componentId, [])
    }
    this.cleanupTasks.get(componentId).push(cleanupFn)
  }

  /**
   * 执行清理任务
   * @param {string} componentId - 组件ID
   */
  executeCleanupTasks(componentId) {
    const tasks = this.cleanupTasks.get(componentId)
    if (tasks && tasks.length > 0) {
      tasks.forEach(task => {
        try {
          task()
        } catch (error) {
          console.error(`清理任务执行失败 (${componentId}):`, error)
        }
      })
    }
  }

  /**
   * 添加待处理操作
   * @param {string} componentId - 组件ID
   * @param {Promise} operation - 操作Promise
   */
  addPendingOperation(componentId, operation) {
    if (!this.pendingOperations.has(componentId)) {
      this.pendingOperations.set(componentId, new Set())
    }
    this.pendingOperations.get(componentId).add(operation)

    // 操作完成后移除
    operation.finally(() => {
      const operations = this.pendingOperations.get(componentId)
      if (operations) {
        operations.delete(operation)
      }
    })
  }

  /**
   * 取消待处理操作
   * @param {string} componentId - 组件ID
   */
  cancelPendingOperations(componentId) {
    const operations = this.pendingOperations.get(componentId)
    if (operations) {
      operations.forEach(operation => {
        if (operation.cancel && typeof operation.cancel === 'function') {
          operation.cancel()
        }
      })
      operations.clear()
    }
  }

  /**
   * 获取组件状态
   * @param {string} componentId - 组件ID
   * @returns {Object|null}
   */
  getComponentState(componentId) {
    return this.components.get(componentId) || null
  }

  /**
   * 获取所有活跃组件
   * @returns {Array}
   */
  getActiveComponents() {
    const activeComponents = []
    this.components.forEach((state, id) => {
      if (this.isActive(id)) {
        activeComponents.push({ id, state })
      }
    })
    return activeComponents
  }

  /**
   * 清理非活跃组件
   * @param {number} maxAge - 最大非活跃时间（毫秒）
   */
  cleanupInactiveComponents(maxAge = 300000) { // 5分钟
    const now = Date.now()
    const toDelete = []

    this.components.forEach((state, id) => {
      if (!state.isActive && (now - state.lastActivity) > maxAge) {
        toDelete.push(id)
      }
    })

    toDelete.forEach(id => {
      console.log(`清理非活跃组件: ${id}`)
      this.markDestroyed(id)
    })
  }

  /**
   * 生成组件ID
   * @param {Object} component - 组件实例
   * @returns {string}
   */
  generateComponentId(component) {
    if (component._uid !== undefined) {
      return `vue_${component._uid}`
    }
    if (component.__wxExparserNodeId__) {
      return `wx_${component.__wxExparserNodeId__}`
    }
    if (component.route) {
      return `page_${component.route}_${Date.now()}`
    }
    return `component_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
  }

  /**
   * 判断是否为微信小程序组件
   * @param {Object} component - 组件实例
   * @returns {boolean}
   */
  isMiniProgramComponent(component) {
    return typeof component.setData === 'function' || 
           component.onLoad !== undefined ||
           component.onShow !== undefined
  }

  /**
   * 判断是否为Vue组件
   * @param {Object} component - 组件实例
   * @returns {boolean}
   */
  isVueComponent(component) {
    return component.$options !== undefined ||
           component._isVue === true ||
           component.$data !== undefined
  }

  /**
   * 内部方法：获取组件状态
   * @param {string} componentId - 组件ID
   * @returns {Object|null}
   */
  _getComponentState(componentId) {
    return this.components.get(componentId) || null
  }

  /**
   * 获取统计信息
   * @returns {Object}
   */
  getStats() {
    const stats = {
      total: this.components.size,
      active: 0,
      mounted: 0,
      destroyed: 0
    }

    this.components.forEach(state => {
      if (state.isActive) stats.active++
      if (state.isMounted) stats.mounted++
      if (state.isDestroyed) stats.destroyed++
    })

    return stats
  }
}

// 创建全局实例
const lifecycleManager = new ComponentLifecycleManager()

// 定期清理非活跃组件
setInterval(() => {
  lifecycleManager.cleanupInactiveComponents()
}, 60000) // 每分钟检查一次

export default lifecycleManager